﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using CrclzChat.Areas.Identity.Data;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace CrclzChat.Models
{
	public class OneContext : IdentityDbContext<OneUser, IdentityRole<Guid>, Guid>
	{

		public OneContext(DbContextOptions<OneContext> options)
			: base(options)
		{
		}

		protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
		{
			var server = Environment.GetEnvironmentVariable("PG_HOST");
			var user = "postgres";
			var db = "chat";
			var pass = Environment.GetEnvironmentVariable("POSTGRES_PASSWORD");
			var str = $"Server={server};Database={db};User ID={user};Password={pass};Timeout=15;CommandTimeout=10000;";
			optionsBuilder.UseNpgsql(str);
		}

		protected override void OnModelCreating(ModelBuilder builder)
		{
			base.OnModelCreating(builder);

			// Foreign Keys

			builder.Entity<APost>()
				.HasOne(p => p.Topic)
				.WithMany(p => p.Posts)
				.HasForeignKey(p => p.TopicId);

			builder.Entity<APost>()
				.HasOne(p => p.User)
				.WithMany(p => p.Posts)
				.HasForeignKey(p => p.UserId);

			builder.Entity<Floor>()
				.HasOne(p => p.User)
				.WithMany(p => p.Floors)
				.HasForeignKey(p => p.UserId);

			builder.Entity<Floor>()
				.HasOne(p => p.Post)
				.WithMany(p => p.Floors)
				.HasForeignKey(p => p.PostId);

			builder.Entity<FloorReply>()
				.HasOne(p => p.User)
				.WithMany(p => p.FloorReplies)
				.HasForeignKey(p => p.UserId);

			builder.Entity<FloorReply>()
				.HasOne(p => p.Floor)
				.WithMany(p => p.FloorReplies)
				.HasForeignKey(p => p.FloorId);

			builder.Entity<Channel>()
				.HasOne(p => p.Floor)
				.WithOne(p => p.Channel)
				.HasForeignKey<Channel>(p => p.FloorId);

			builder.Entity<ChannelMessage>()
				.HasOne(p => p.User)
				.WithMany(p => p.ChannelMessages)
				.HasForeignKey(p => p.UserId);

			builder.Entity<ChannelMessage>()
				.HasOne(p => p.Channel)
				.WithMany(p => p.ChannelMessages)
				.HasForeignKey(p => p.ChannelId);
		}
	}
}
